<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <!--      <el-form-item label="日期" prop="startTime">-->
      <!--        <el-date-picker-->
      <!--          @change="startTimeChange"-->
      <!--          value-format="yyyy-MM-dd"-->
      <!--          v-model="queryParams.startTime"-->
      <!--          type="date"-->
      <!--          placeholder="选择日期"-->
      <!--        >-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <el-form-item label="日期" prop="startTime">
        <el-date-picker
          @change="dateRangeChange"
          value-format="yyyy-MM-dd"
          v-model="dateRange"
          type="daterange"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="房间" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="20" class="mb20">
      <el-col :span="1.5">
        <el-button @click="handleBatchDialogVisible">批量修改价格</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="list"
      ref="table"
      border
    >
      <el-table-column
        label="房间名称"
        prop="house.premisesAddress"
        :show-overflow-tooltip="true"
        fixed="left"
        min-width="300"
        :resizable="false"
      />
      <el-table-column v-for="(date) in dateList" :key="date.date" :resizable="false">
        <template #header>
          <div
            style="display: flex; flex-direction: column; align-items: center"
          >
            <div>{{ date.date.slice(5) }}</div>
            <div>{{ date.title }}</div>
          </div>
        </template>
        <template #default="scope">
          <div @click="putPrice(date, scope.row)" style="cursor: pointer">
            {{ priceFormat(date, scope.row) }}
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />
    <!-- 修改房费 -->
    <el-dialog
      title="修改房费"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <div>
        <el-form ref="form" :rules="rules" :model="form" label-width="80px">
          <el-form-item label="改价日期">
            <el-input
              :disabled="true"
              v-model="form.calendarTime"
              placeholder=""
            ></el-input>
          </el-form-item>
          <el-form-item label="改后价格" prop="calendarPrice">
            <el-input
              v-model="form.calendarPrice"
              placeholder=""
              v-input.float="2"
              @change="(e)=>form.calendarPrice= Number(e)"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="改价房间">
            <el-input
              :disabled="true"
              v-model="form.premisesAddress"
              placeholder=""
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 批量修改房费 -->
    <el-dialog
      title="批量修改房费"
      :visible.sync="batchDialogVisible"
      width="500"
      :before-close="handleClose"
    >
      <div>
        <el-form
          ref="batchform"
          :model="batchform"
          :rules="batchRules"
          label-width="80px"
        >
          <el-form-item label="改价日期" prop="times">
            <el-date-picker
              v-model="batchform.times"
              type="daterange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="改后价格" prop="calendarPrice">
            <el-input
              v-model="batchform.calendarPrice"
              placeholder=""
              v-input.float="2"
              @change="(e)=>batchform.calendarPrice= Number(e)"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="改价房间" prop="houseIds">
            <el-button size="small" @click="dialogSelectHouseVisible = true"
            >添加
            </el-button
            >
          </el-form-item>
        </el-form>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="date" label="房间">
            <template #default="scope">
              {{ scope.row.house.estateName }}
              {{ scope.row.house.buildingName }}栋
              {{ scope.row.house.unitName }}单元
              {{ scope.row.house.roomNumber }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作">
            <template #default="scope">
              <el-button type="text" @click="delHouse(scope.$index)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="batchDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="batchSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <SelectHouse v-model="dialogSelectHouseVisible" @success="selectHouseCb" :selectedData="tableData"
                 :is-multiple="true"
    />
  </div>
</template>

<script>
import {
  listByAllocation,
  calendarPrice,
  putCalendarPrice,
  editBatch
} from '@/api/house/price'
import { getDayOrWeek, getKeyWeek } from '@/utils/common/time'
import SelectHouse from './components/select-house.vue'
import { diffDays, getDate } from '@/utils/common/moment'

export default {
  name: 'calendarPriceCom',
  dicts: [],
  watch: {
    tableData: {
      handler(newVal) {
        let arr = []
        newVal.forEach((item) => {
          arr.push(item.houseId)
        })
        this.batchform.houseIds = arr
      },
      immediate: true
    },
    'batchform.times': {
      handler(newVal) {
        this.batchform.startTime = newVal[0]
        this.batchform.endTime = newVal[1]
      },
      immediate: true
    }
  },
  computed: {
    dateList: {
      get() {
        let startDate = new Date(this.queryParams.startTime).valueOf()
        // let endDate =
        //   new Date(this.queryParams.startTime).valueOf() +
        //   60 * 60 * 24 * 1000 * 30

        let endDate = new Date(this.queryParams.endTime).valueOf()
        return this.getDates(startDate, endDate)
      },
      set(v) {
      }
    }
  },
  components: { SelectHouse },
  data() {
    return {
      drawer: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 当前选择
      current: 'all',
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],

      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomNumber: undefined,
        status: undefined,
        startTime: '',
        endTime: '',
        'housingAllocation.apartmentState': '',
        keyword: ''
      },
      countHouseList: [],
      // 表单参数
      form: {
        id: '', //日历价格id
        allocationId: '', //配置id
        houseId: '', //房屋id
        calendarTime: '', //日历日期
        calendarPrice: null //日历价格
      },
      batchform: {
        times: [],
        houseIds: [], //房屋id集合
        startTime: '', //日历开始时间
        endTime: '', //日历结束时间
        calendarPrice: null //日历价格
      },
      rules: {
        calendarPrice: [
          {
            required: true,
            message: '请输入改后价格',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error('数字须大于0'))
              }
              let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{2})$/
              if (value.toString().includes('.') && !reg.test(value)) {
                callback(new Error('小数点后限两位'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      batchRules: {
        times: [
          {
            required: true,
            type: 'array',
            message: '请选择时间',
            trigger: 'change'
          }
        ],
        houseIds: [
          {
            required: true,
            type: 'array',
            message: '请选择房间',
            trigger: 'change'
          }
        ],
        calendarPrice: [
          {
            required: true,
            message: '请输入改后价格',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                return callback(new Error('数字须大于0'))
              }
              let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{2})$/
              if (value.toString().includes('.') && !reg.test(value)) {
                callback(new Error('小数点后限两位'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      detailDialogVisible: false,
      orderId: '',
      openChangeHouse: false,
      openEdit: false,
      orderInfo: {},
      addDialogVisible: false, //新建弹窗，
      openmembershipRegistration: false,
      activeName: 'first',
      estateList: [],
      dialogVisible: false,
      batchDialogVisible: false,
      tableData: [],
      dialogSelectHouseVisible: false,
    }
  },
  created() {
    this.queryParams.startTime = getDate(new Date(), 0, 'YYYY-MM-DD', 'days')
    this.queryParams.endTime = getDate(this.queryParams.startTime, 30, 'YYYY-MM-DD', 'days')
    this.dateRange = [this.queryParams.startTime, this.queryParams.endTime]
    this.getList()
  },
  activated() {
    this.getList()
  },
  methods: {
    handleBatchDialogVisible() {
      this.tableData = []

      this.batchform = {
        times: [],
        houseIds: [], //房屋id集合
        startTime: '', //日历开始时间
        endTime: '', //日历结束时间
        calendarPrice: null //日历价格
      }
      this.batchDialogVisible = true
    },
    delHouse(index) {
      this.tableData.splice(index, 1)
    },
    //房间选择回调
    selectHouseCb(data) {
      // this.tableData.push(...data);
      // function uniqueObjectsByProperty(arr, key) {
      //   const unique = {};
      //   arr.forEach((item) => {
      //     if (!unique.hasOwnProperty(item[key])) {
      //       unique[item[key]] = item;
      //     }
      //   });
      //   return Object.values(unique);
      // }
      // this.tableData = uniqueObjectsByProperty(this.tableData, "houseId");

      // this.tableData = [...new Set([...this.tableData,...data])];

      this.tableData = data
    },
    onSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id) {
            putCalendarPrice(this.form).then((response) => {
              this.$modal.msgSuccess(response.msg)
              this.getList()
              this.dialogVisible = false
            })
          } else {
            calendarPrice(this.form).then((response) => {
              this.$modal.msgSuccess(response.msg)
              this.getList()
              this.dialogVisible = false
            })
          }
        }
      })
    },
    batchSubmit() {
      this.$refs['batchform'].validate((valid) => {
        if (valid) {
          editBatch(this.batchform).then((response) => {
            this.$modal.msgSuccess(response.msg)
            this.getList()
            this.batchDialogVisible = false
          })
        }
      })
    },
    putPrice(date, row) {
      let price = row.calendarPriceList.find((item) => {
        return date.date == item.calendarTime
      })
      this.form = Object.assign({}, price)
      this.form.premisesAddress = row.house.premisesAddress
      console.log('form',this.form)
      this.dialogVisible = true
    },
    getDataList() {
      let startDate =
        new Date(this.queryParams.startTime).valueOf() - 60 * 60 * 24 * 1000
      let endDate =
        new Date(this.queryParams.startTime).valueOf() +
        60 * 60 * 24 * 1000 * 30
      return this.getDates(startDate, endDate)
    },
    openInfo() {
      this.drawer = true
    },
    handleClick() {
    },
    handleClose(done) {
      done()
    },
    startTimeChange() {
      this.getList()
      this.$forceUpdate()
    },
    // 日期范围改变
    dateRangeChange(value) {
      if (value) {
        let day = diffDays(value[0], value[1])
        if(day > 30){
          this.$message.error('日期间隔不能大于30天')
          return
        }
        this.queryParams.startTime = value[0]
        this.queryParams.endTime = value[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
      this.getList()
      this.$forceUpdate()
    },

    //生成日期列表
    getDates(date1, date2, format) {
      let dates = []
      let [startDate, endDate] =
        new Date(date1) < new Date(date2)
          ? [new Date(date1), new Date(date2)]
          : [new Date(date2), new Date(date1)]
      while (startDate <= endDate) {
        dates.push(new Date(startDate))
        startDate.setDate(startDate.getDate() + 1)
      }
      dates = dates.map((item) => {
        item = item
          .toLocaleDateString()
          .split('/')
          .map((items) => {
            items = items.padStart(2, '0')
            return items
          })
          .join(format || '-')
        return {
          date: item,
          status: undefined,
          title: getDayOrWeek(item),
          key: getKeyWeek(item)
        }
      })
      return dates
    },
    priceFormat(date, row) {
      if (row.calendarPriceList) {
        let price
        price = row.calendarPriceList.find((item) => {
          return date.date == item.calendarTime
        })
        return price && price.calendarPrice ? `￥${price.calendarPrice}` : ''
      } else {
        let price
        price = row.priceMap.find((item) => {
          return date.key == item.week
        })
        return price && price ? `￥${price.housePrice}` : ''
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      // this.queryParams.startTime = this.dateList[0].date
      // this.queryParams.endTime = this.dateList[this.dateList.length - 1].date

      listByAllocation(this.addDateRange(this.queryParams, this.dateRange)).then((response) => {
        this.list = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.queryParams.startTime = getDate(new Date(), 0, 'YYYY-MM-DD', 'days')
      this.queryParams.endTime = getDate(this.queryParams.startTime, 30, 'YYYY-MM-DD', 'days')
      this.dateRange = [this.queryParams.startTime, this.queryParams.endTime]
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.queryParams.orderIds = this.ids
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.orderId = ''
      this.addDialogVisible = true
    },
    // 详情操作
    handleDetail(row) {
      this.orderId = row.orderId
      this.detailDialogVisible = true
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.orderInfo = row
      this.openEdit = true
    },
    //换房操作
    handleChangeHouse(row) {
      this.orderInfo = row
      this.openChangeHouse = true
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'enterprise/order/order/export',
        {
          ...this.queryParams
        },
        `订单_${new Date().getTime()}.xlsx`
      )
    },
    //请空选择项
    clearSelect() {
      this.$refs.table.clearSelection()
    }
  }
}
</script>
<style lang="scss" scoped>
.title {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}

.total {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-top: 6px;
}

.left-border {
  border-left: 1px solid #999;
}

.right-border {
  border-right: 1px solid #999;
}

.info {
  padding: 10px 15px;
  margin: 15px 0;
  background: #e6f7ff;
  color: #1890ff;

  span {
    color: #565c5f;
  }

  .clear {
    margin-left: 20px;
    cursor: pointer;
  }
}

.calendar-status {
  width: 60px;
  height: 30px;
  background-color: green;
  cursor: pointer;
}
</style>
